<?php


namespace app\wenchuang\controller;


use app\wenchuang\model\WorkModel;
use app\wenchuang\validate\WorkValidate;
use cmf\controller\AdminBaseController;

class WorkController extends AdminBaseController
{
      public function index()
      {
          $work = WorkModel::order('list_order','desc')->select();
          $this->assign('work', $work);
          return $this->fetch();
      }

    //排序
    public function listOrder()
    {
        parent::listOrders(new WorkModel());
        $this->success('排序成功');
    }

         // 显示添加页面
      public function add()
      {
          return $this->fetch();
      }
      public function addpost()
      {
          $data = $this->request->param();
          //过滤掉富文本添加的html标签
          $data['content'] = html_entity_decode($data['content']);
          // 验证数据
          $validate = new WorkValidate();
          $result = $validate->scene('add')->check($data);
          if ($result !== true) {
              $this->error($validate->getError());
          }
          // 存库
          $bannerModel = New WorkModel();
          if ($bannerModel->save($data)) {
              $this->success('添加成功', 'Work/index');
          }
          $this->error('添加失败');
      }
    // 显示修改页面
    public function edit()
    {
        $id = $this->request->param('id');
        $work = WorkModel::find($id);
        //显示编辑页面也要处理存在数据库的富文本
        $work['content'] = cmf_replace_content_file_url(htmlspecialchars_decode($work['content']));
        $this->assign('work', $work);
        return $this->fetch();
    }
    // 编辑保存
    public function editPost()
    {
        $data = $this->request->param();
        $data['content'] = html_entity_decode($data['content']);
        // 验证数据
        $validate = new WorkValidate();
        $result = $validate->scene('add')->check($data);
        if ($result !== true) {
            $this->error($validate->getError());
        }
        // 编辑存库
        $workModel = New WorkModel();
        $work = $workModel->where('id', '=', $data['id'])->find();
        $work->title = $data['title'];
        $work->abstract = $data['abstract'];
        $work->image = $data['image'];
        $work->content = $data['content'];
        $work->author = $data['author'];
        if ($work->save()) {
            $this->success('保存成功', 'Work/index');
        }
        $this->error('保存失败');
    }
    // 删除
       public function softDelete()
      {
        $id = input('id');
        $workModel = New WorkModel();
        // 查询要删除的数据
        $work = $workModel->where('id', '=', $id)->find();
        if ($work->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}